#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:Closure.py
# author:张仁
# datetime:2021/3/18 20:10
# software: PyCharm
"""
    利用闭包返回一个计数器函数，每次调用它返回递增整数：
"""


def createCounter():
    """
        通过列表的形式设置函数内的全局变量
            实现每次调用count会加一
    """
    count = [0]

    def addCounter():
        count[0] += 1
        return count[0]

    return addCounter


def createCounter2():
    """
         通过nonlocal的形式设置函数内的全局变量
             实现每次调用count会加一
    """
    count = 0

    def addCounter():
        nonlocal count
        count += 1
        return count

    return addCounter


if __name__ == '__main__':
    counterA = createCounter()
    print(counterA(), counterA(), counterA(), counterA(), counterA())  # 1 2 3 4 5
    counterB = createCounter()
    if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
        print('测试通过!')
    else:
        print('测试失败!')
